package com.shibaobei.activity.controller;


import com.shibaobei.activity.model.Template;
import com.shibaobei.activity.service.FormTemplateService;
import com.shibaobei.activity.service.ProcessDefinitionService;
import com.shibaobei.activity.utils.UploadFileUtils;
import org.activiti.engine.impl.util.json.JSONObject;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by Administrator on 2020/5/1 0001.
 */
@Controller
@RequestMapping("/formTemplate")
public class FormTemplateController {
    @Autowired
    private FormTemplateService templateService;
    @Autowired
    private ProcessDefinitionService processDefinitionService;


    @RequestMapping("/list")
    public String formTemplate(Model model){
        List<Template> list = templateService.findList();
        model.addAttribute("templateList",list);
        return "Flow_FormTemplate/list";
    }

    @RequestMapping("/saveUI")
    public String saveUI(Model model){
        List<ProcessDefinition> lastList = processDefinitionService.findLastList();
        model.addAttribute("lastList",lastList);
        return "Flow_FormTemplate/saveUI";
    }

    /**
     * 添加表单模板
     * @return
     */
    @RequestMapping("/add")
    public ModelAndView add(Template template, MultipartFile resource) throws IOException {

        String targetPath = UploadFileUtils.copy(resource);
        template.setDocFilePath(targetPath);
        templateService.addTemplate(template);
        ModelAndView mv = new ModelAndView();
        //使用重定向，此时springmvc.xml配置文件中的视图解析器将会失效
        mv.setViewName("redirect:/formTemplate/list");
        return mv;

    }

    /**
     * 删除流程模板,同时删除doc文件
     * @param id
     * @return
     */
    @RequestMapping("/deleteTemplate")
    @ResponseBody
    public JSONObject deleteTemplate(String id){
        Template template = templateService.getTemplateById(id);
        String docFilePath = template.getDocFilePath();
        File file = new File(docFilePath);
        if(file.exists()){
            file.delete();
        }
        templateService.deleteTemplate(id);
        JSONObject json = new JSONObject();
        json.put("success",true);
        return json;

    }

    /**
     * 下载模板文档
     */
    @RequestMapping("/downloadDoc")
    public void downloadDoc(HttpServletResponse response, String id) throws UnsupportedEncodingException {
        Template template = templateService.getTemplateById(id);
        //待下载文件名
        String fileName = template.getDocFilePath();
        //设置为png格式的文件
        response.setHeader("content-type", "doc");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();

            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File(fileName )));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }






}

